<template>
  <el-dialog
    :title="isEditing ? '编辑员工' : '添加员工'"
    v-model="isFormVisible"
    @close="$emit('cancel')"
  >
    <el-form :model="formData" :rules="rules" ref="formRef">
      <el-form-item label="姓名" prop="name">
        <el-input v-model="formData.name"></el-input>
      </el-form-item>
      <el-form-item label="部门" prop="department">
        <el-select v-model="formData.department" placeholder="请选择部门">
          <el-option label="技术部" value="技术部"></el-option>
          <el-option label="市场部" value="市场部"></el-option>
          <el-option label="财务部" value="财务部"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="职位" prop="position">
        <el-input v-model="formData.position"></el-input>
      </el-form-item>
      <el-form-item label="薪资" prop="salary">
        <el-input-number v-model="formData.salary" :min="0"></el-input-number>
      </el-form-item>
      <el-form-item label="入职日期" prop="hireDate">
        <el-date-picker
          v-model="formData.hireDate"
          type="date"
          placeholder="选择日期"
        ></el-date-picker>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="$emit('cancel')">取消</el-button>
      <el-button type="primary" @click="submitForm">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, watch } from 'vue';
import useVuelidate from '@vuelidate/core';
import { required, minLength, minValue } from '@vuelidate/validators';

const props = defineProps({
  isEditing: Boolean,
  employee: Object
});

const emit = defineEmits(['submit', 'cancel']);

const isFormVisible = ref(true);
const formRef = ref(null);

const formData = reactive({
  id: null,
  name: '',
  department: '',
  position: '',
  salary: 0,
  hireDate: null
});

const rules = {
  name: { required, minLength: minLength(2) },
  department: { required },
  position: { required },
  salary: { required, minValue: minValue(0) },
  hireDate: { required }
};

const v$ = useVuelidate(rules, formData);

watch(() => props.employee, (newVal) => {
  if (newVal) {
    Object.assign(formData, newVal);
  }
});

const submitForm = async () => {
  const result = await v$.value.$validate();
  if (!result) {
    return;
  }
  emit('submit', { ...formData });
};
</script>